<?php
class UsersController extends AppController {
	public function beforeFilter() {
		parent::beforeFilter();
		
		$this->Auth->allow('admin_add', 'register');
	}
	

/**
 * Login + Logout function
 */
	public function admin_login() {
		$this->layout = 'login';
		$this->set('title_for_layout', __('Admin Login'));
	}
	
	public function admin_logout() {
		;
	}
	
	public function login() {
		$this->layout = 'login';
		$this->set('title_for_layout', __('Login'));
		
	}
	
	public function logout() {
		;
	}

/**
 * Inside function
 */
	public function admin_index() {
		$this->set('title_for_layout', __('Xin chào, tôi là Admin Index'));
	}
	
	public function admin_add() {
		$this->set('title_for_layout', __('Create new User'));
	}
	
	public function admin_edit() {
		;
	}
	
	public function admin_profile() {
		;
	}
	
	public function index() {
		$this->set('title_for_layout', __('Xin chào, tôi là Index'));
	}
	
	public function profile() {
		
	}
	
	public function register() {
		$this->layout = 'login';
		$this->set('title_for_layout', __('Register'));
		$this->set('page_title', __('Register New Account'));
		
		if (!empty($this->request->data)) {
			$userData = $this->request->data;
			
			$userData['User']['group'] = GROUP_USER;
			
			$this->User->set($userData);
			if ($this->User->validates($userData)) {
				$userData['User']['created'] = $userData['User']['updated'] = date('Y-m-d H:i:s');
			
				if ($this->User->save($userData)) {
					$this->Session->setFlash(__('Your account has been created.<br> Check your email to confirm your registeration.'), 'default', array('class' => 'alert alert-success'));
					$this->redirect(array('action' => 'login'));
				} else {
					$this->Session->setFlash(__('Unexpected error happens. Please try again.'), 'default', array('class' => 'alert alert-success'));
				}
			} else {
				$errors = $this->User->validationErrors;
				if (!empty($errors) && is_array($errors)) {
					foreach ($errors as $key => $error) {
						$this->Session->setFlash($error[0], 'default', array('class'=> 'alert alert-error'));
					}
				}
			}
		}
	}
	
	public function recover() {
		
	}
}